<script setup>
	import { ref, onMounted, nextTick } from 'vue'
	import { onShow } from '@dcloudio/uni-app'
	import { useUserStore } from '@/store/userInfo'
	import { useAddressStore } from '@/store/address'
	import { useCartStore } from '@/store/cart'
	import { useShopStore } from '@/store/shop'
	// 接收我的页面跳转参数
	const props = defineProps( {
		state: String
	} )
	// 根据跳转状态渲染数据
	const stateOrderGet = ( ) => {
		if ( props.state === '待付款' ) activeState.value = 1
		if ( props.state === '待发货' ) activeState.value = 2
		if ( props.state === '待取货' ) activeState.value = 3
		if ( props.state === '全部' ) activeState.value = 0
	}

	// 状态常量
	const ORDER_STATES = [ '全部', '待付款', '待发货', '待取货', '已完成' ]

	const userStore = useUserStore( )
	const addressStore = useAddressStore( )
	const cartStore = useCartStore( )
	const shopStore = useShopStore( )
	const orderApi = uniCloud.importObject( 'order' )

	// 当前选中的状态
	const activeState = ref( 0 )
	// 订单列表
	const orderList = ref( [ ] )
	// 倒计时数据 - 使用 Map 结构存储
	const timeDataMap = new Map( )

	// 检查登录状态
	const checkLogin = ( ) => {
		if ( !userStore.userInfo.uid ) {
			uni.showModal( {
				title: '提示',
				content: '请先登录',
				confirmText: "去登录",
				success( res ) {
					if ( res.confirm ) {
						uni.navigateTo( { url: "/pages/login/login" } )
					} else {
						uni.switchTab( { url: '/pages/index/index' } )
					}
				}
			} )
			return false
		}
		return true
	}

	// 获取订单列表
	const getOrderList = async ( state = 0 ) => {
		if ( !checkLogin( ) ) return

		try {
			console.log( '获取订单列表，状态:', state )
			const result = await orderApi.getOrderList( userStore.userInfo.uid, state )
			if ( result.errCode === 0 ) {
				orderList.value = result.data
				console.log( '获取订单成功:', result.data )
			} else {
				uni.showToast( {
					title: result.errMsg,
					icon: 'none'
				} )
			}
		} catch ( error ) {
			console.error( '获取订单失败:', error )
			uni.showToast( {
				title: '获取订单失败',
				icon: 'none'
			} )
		}
	}

	// 切换状态
	const changeState = ( state ) => {
		activeState.value = Number( state )
		getOrderList( activeState.value )
	}

	// 计算倒计时时间（分钟）
	const getCountdownMinutes = ( createTime ) => {
		const now = Date.now( )
		const deadline = createTime + ( 10 * 60 * 1000 ) // 10分钟期限
		const remaining = Math.max( 0, deadline - now )
		return Math.floor( remaining / ( 1000 * 60 ) ) // 向下取整，确保不会超过实际时间
	}

	// 倒计时结束处理
	const timeup = async ( order_no ) => {
		try {
			const result = await orderApi.deleteOrder( order_no )
			if ( result.errCode === 0 ) {
				uni.showToast( {
					title: '订单已超时自动取消',
					icon: 'none'
				} )
				// 延迟刷新列表
				setTimeout( ( ) => {
					getOrderList( activeState.value )
				}, 100 )
			}
		} catch ( error ) {
			console.error( '删除超时订单失败:', error )
		}
	}

	// 取消订单处理
	const cancelOrder = ( order_no ) => {
		if ( !checkLogin( ) ) return
		uni.showModal( {
			title: '提示',
			content: '确定要取消该订单吗？',
			success: async ( res ) => {
				if ( res.confirm ) {
					try {
						const result = await orderApi.deleteOrder( order_no )
						if ( result.errCode === 0 ) {
							uni.showToast( {
								title: '订单已取消',
								icon: 'success'
							} )
							getOrderList( activeState.value )
						} else {
							uni.showToast( {
								title: result.errMsg || '取消失败',
								icon: 'none'
							} )
						}
					} catch ( error ) {
						console.error( '取消订单失败:', error )
						uni.showToast( {
							title: '取消订单失败',
							icon: 'none'
						} )
					}
				}
			}
		} )
	}

	// 确认收货处理
	const confirmReceive = ( order_no ) => {
		if ( !checkLogin( ) ) return
		uni.showModal( {
			title: '提示',
			content: '确认已收到商品？',
			success: async ( res ) => {
				if ( res.confirm ) {
					try {
						const result = await orderApi.updateOrderState( order_no, 4 )
						if ( result.errCode === 0 ) {
							uni.showToast( {
								title: '确认收货成功',
								icon: 'success'
							} )
							getOrderList( activeState.value )
						} else {
							uni.showToast( {
								title: result.errMsg,
								icon: 'none'
							} )
						}
					} catch ( error ) {
						uni.showToast( {
							title: '确认收货失败',
							icon: 'none'
						} )
					}
				}
			}
		} )
	}
	const goPay = ref( null )
	// 点击继续支付
	const openPay = async ( orderData ) => {
		console.log( orderData )
		// 调起支付
		await goPay.value.createOrder( {
			order_no: orderData.order_no,
			provider: 'wxpay',
			total_fee: orderData.tatalPrice * 100, // 转换为分为单位
			type: 'goods',
			description: '商品订单'
		} )
	}
	// 点击再次购买
	const againPay = async ( lastOrderData ) => {
		console.log( lastOrderData )
		// 检查收货地址
		if ( !lastOrderData.address ) {
			uni.showToast( {
				title: '请选择收货地址',
				icon: 'none'
			} )
			return
		}

		// 构建订单数据
		const orderData = {
			cart_list: lastOrderData.cart_list,
			address: lastOrderData.address,
			recipient: lastOrderData.recipient,
			recipientMobile: lastOrderData.recipientMobile,
			tatalPrice: lastOrderData.tatalPrice,
			num: lastOrderData.num,
			state: 1
		}

		// 调用云对象创建订单
		const result = await orderApi.add( userStore.userInfo.uid, orderData )
		console.log( result )
		// 调起支付
		const resPay = await goPay.value.createOrder( {
			order_no: result.order_no,
			provider: 'wxpay',
			total_fee: orderData.tatalPrice * 100, // 转换为分为单位
			type: 'goods',
			description: '商品订单'
		} )
		console.log( resPay, '购买成功之后' )
	}
	// 支付成功
	const onSuccess = ( res ) => {
		console.log( '支付成功', res )
		cartStore.clearCart( )
	}
	// 支付取消
	const onCancel = ( res ) => {
		console.log( '支付取消', res )
		uni.showToast( {
			icon: "none",
			title: "取消支付",
			mask: true
		} )
	}
	// 回到首页
	const goHome = ( ) => {
		uni.switchTab( { url: "/pages/index/index" } )
	}

	// 跳转到订单详情
	const goToDetail = ( orderId ) => {
		if ( !checkLogin( ) ) return

		uni.navigateTo( {
			url: `/pages/order/orderDetail?orderId=${orderId}`
		} )
	}

	// 页面加载时获取订单
	onMounted( ( ) => {
		// 根据所传参数渲染订单
		stateOrderGet( )
		if ( checkLogin( ) ) {
			getOrderList( activeState.value )
		}
	} )

	// 添加 onShow 生命周期
	onShow( ( ) => {
		// 如果已登录，则刷新当前状态的订单列表
		if ( checkLogin( ) ) {
			getOrderList( activeState.value )
		}
	} )
</script>

<template>
	<view class="order">
		<!-- 状态切换 -->
		<view class="state-switch">
			<view class="state-item" v-for="(item, index) in ORDER_STATES" :key="index"
				:class="{ active: activeState === index }" @tap="changeState(index)">
				{{ item }}
			</view>
		</view>

		<!-- 订单列表 -->
		<view class="order-list">
			<view v-if="!orderList || orderList.length === 0" class="empty-tip">
				暂无相关订单
			</view>
			<view v-for="item in orderList" :key="item._id" class="order-item"
				@tap="goToDetail(item._id)">
				<!-- 订单头部 -->
				<view class="order-header">
					<view class="shop-info">
						<text class="shop-name">{{shopStore.shopInfo.shop_name}}</text>
						<uni-dateformat :date="item.create_time" format="yyyy-MM-dd hh:mm:ss"
							class="order-time" />
					</view>
					<text class="order-status" :class="{
						'wait-pay': item.state === 1,
						'wait-send': item.state === 2,
						'wait-receive': item.state === 3,
						'completed': item.state === 4
					}">{{ ORDER_STATES[item.state] }}</text>
				</view>

				<!-- 商品信息 -->
				<view class="goods-info">
					<view class="goods-images">
						<image v-for="goods in item.cart_list.slice(0, 3)" :key="goods._id"
							:src="goods.cover_pic" class="goods-image" mode="aspectFill" />
						<view class="arrow-right" v-if="item.cart_list.length > 3">
							<uni-icons custom-prefix="iconfont" type="yuan-a-ArrowRight2" color="#ced4da"
								:size="20" />
						</view>
					</view>
					<view class="total-info">
						<text class="price">¥{{ item.tatalPrice.toFixed(2) }}</text>
						<text class="count">共{{ item.num }}件</text>
					</view>
				</view>

				<!-- 配送地址 -->
				<view class="delivery-address" v-if="item.state === 2">
					<text class="address-text">配送地址：{{ item.address }}</text>
				</view>

				<!-- 倒计时 -->
				<view class="countdown" v-if="item.state === 1">
					<view class="countdown-wrapper">
						<text class="countdown-label">支付剩余时间：</text>
						<uni-countdown :key="item._id" :day="0" :hour="0"
							:minute="getCountdownMinutes(item.create_time)" :second="0" :show-day="false"
							:show-colon="true" :font-size="14" color="#ff3c2a" backgroundColor="#fff5f4"
							borderColor="#ffccc7" :start="true" @timeup="() => timeup(item.order_no)" />
						<text class="countdown-suffix">后订单关闭</text>
					</view>
				</view>

				<!-- 按钮组 -->
				<view class="order-footer">
					<view class="btn-group">
						<!-- 待付款状态 -->
						<template v-if="item.state === 1">
							<button class="btn cancel" @tap.stop="cancelOrder(item.order_no)">取消订单</button>
							<button class="btn pay" @tap.stop="openPay(item)">继续支付</button>
						</template>
						<!-- 待发货状态 -->
						<template v-if="item.state === 2">
							<button class="btn outline">查看订单</button>
						</template>
						<!-- 待取货状态 -->
						<template v-if="item.state === 3">
							<button class="btn confirm" @tap.stop="confirmReceive(item.order_no)">确认收货</button>
						</template>
						<!-- 已完成状态 -->
						<template v-if="item.state === 4">
							<button class="btn cancel" @tap.stop="cancelOrder(item.order_no)">删除订单</button>
							<button class="btn rebuy" @tap.stop="againPay(item)">再次购买</button>
						</template>
					</view>
				</view>
			</view>
		</view>
		<uni-pay ref="goPay" returnUrl="/pages/order/order" @success="onSuccess"
			@cancel="onCancel"></uni-pay>
		<view class="footer">
			<view class="btn" @tap="goHome">
				回到首页
			</view>
		</view>
	</view>
</template>

<style lang="scss" scoped>
	.order {
		@include pageStyle;
		padding-bottom: 300rpx;

		/* 顶部状态切换栏 */
		.state-switch {
			display: flex;
			justify-content: space-between;
			padding: 0 32rpx;
			background-color: #fff;
			border-bottom: 1px solid $line-color-aux;

			.state-item {
				position: relative;
				padding: 24rpx 0;
				font-size: 28rpx;
				color: #666;

				/* 激活状态样式 */
				&.active {
					color: $brand-theme-color;
					font-weight: bold;

					/* 底部蓝色浮标 */
					&::after {
						content: '';
						position: absolute;
						left: 50%;
						bottom: 16rpx;
						transform: translateX(-50%);
						width: 40rpx;
						height: 4rpx;
						background-color: $brand-theme-color;
						border-radius: 2rpx;
					}
				}
			}
		}

		/* 订单列表区域 */
		.order-list {
			padding: 24rpx;

			/* 单个订单卡片 */
			.order-item {
				margin-bottom: 24rpx;
				padding: 24rpx;
				background-color: #fff;
				border-radius: 16rpx;

				/* 订单头部：店铺信息和订单状态 */
				.order-header {
					display: flex;
					justify-content: space-between;
					margin-bottom: 24rpx;

					.shop-info {

						/* 店铺名称-渐变文字 */
						.shop-name {
							@include shopName;
						}

						/* 订单时间 */
						.order-time {
							font-size: 24rpx;
							color: $text-font-color-3;
						}
					}

					/* 订单状态文本 */
					.order-status {
						font-size: 28rpx;
						color: #ff4d4f;

						/* 待付款状态的颜色 */
						&.wait-pay {
							color: #ff4d4f;
						}

						/* 待发货状态的颜色 */
						&.wait-send {
							color: #faad14;
						}

						/* 待收货状态的颜色 */
						&.wait-receive {
							color: #1890ff;
						}

						/* 已完成状态的颜色 */
						&.completed {
							color: #52c41a;
						}
					}
				}

				/* 商品信息区域：图片列表和总价 */
				.goods-info {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin: 24rpx 0;

					/* 商品图片列表 */
					.goods-images {
						display: flex;
						align-items: center;

						/* 单个商品图片 */
						.goods-image {
							width: 140rpx;
							height: 140rpx;
							border-radius: 16rpx;
							margin-right: 16rpx;
							border: 4px solid $line-color-aux;
						}

						/* 更多商品箭头图标 */
						.arrow-right {
							display: flex;
							align-items: center;
							margin-left: 8rpx;
						}
					}

					/* 总价信息 */
					.total-info {
						text-align: right;

						/* 总价 */
						.price {
							display: block;
							font-size: 32rpx;
							font-weight: bold;
							margin-bottom: 8rpx;
							color: $text-font-color-2;
						}

						/* 总件数 */
						.count {
							font-size: 24rpx;
							color: $text-font-color-3;
						}
					}
				}

				/* 配送地址区域 - 待发货状态显示 */
				.delivery-address {
					margin: 24rpx 0;
					padding: 16rpx;
					background-color: #f8f8f8;
					border-radius: 16rpx;

					.address-text {
						font-size: 24rpx;
						color: $text-font-color-3;
					}
				}

				/* 倒计时区域 - 待付款状态显示 */
				.countdown {
					margin: 24rpx 0;
					display: flex;
					justify-content: flex-start;
					align-items: center;

					.countdown-wrapper {
						display: flex;
						align-items: center;
						font-size: 24rpx;
						color: #ff3c2a;

						.countdown-label {
							margin-right: 8rpx;
						}

						.countdown-suffix {
							margin-left: 8rpx;
						}
					}
				}

				/* 物流信息区域 - 待取货状态显示 */
				.delivery-info {
					margin: 24rpx 0;
					padding: 16rpx;
					background-color: #f8f8f8;
					border-radius: 16rpx;

					.info-item {
						font-size: 24rpx;
						color: $text-font-color-3;
						line-height: 1.6;

						.label {
							display: inline-block;
							width: 140rpx;
						}

						.value {
							color: $text-font-color-2;
						}
					}
				}

				/* 底部按钮区域 */
				.order-footer {
					display: flex;
					justify-content: flex-end;
					margin-top: 24rpx;
					width: 100%;

					/* 按钮组 */
					.btn-group {
						display: inline-flex;
						justify-content: flex-end;
						align-items: center;

						/* 按钮基础样式 */
						.btn {
							min-width: 140rpx;
							height: 52rpx;
							line-height: 52rpx;
							padding: 0 24rpx;
							font-size: 24rpx;
							border-radius: 26rpx;
							margin-left: 16rpx;
							text-align: center;
							flex-shrink: 0;

							&:first-child {
								margin-left: 0;
							}

							/* 取消按钮样式 */
							&.cancel {
								color: #666;
								background-color: #fff;
								border: 1px solid #ddd;
							}

							/* 支付按钮样式 */
							&.pay {
								color: #fff;
								background-color: #ed544f;
								border: none;
							}

							/* 镂空按钮样式 */
							&.outline {
								color: #2979ff;
								background-color: #fff;
								border: 1px solid #2979ff;
							}

							/* 确认收货按钮样式 */
							&.confirm {
								color: #fff;
								background-color: #28A745;
								border: none;
							}

							/* 再次购买按钮样式 */
							&.rebuy {
								color: #fff;
								background-color: #ed544f;
								border: none;
							}
						}
					}
				}

				/* 添加点击效果 */
				&:active {
					opacity: 0.8;
				}
			}
		}

		/*回到首页*/
		.footer {
			@include pageBtnStyle;

			.btn {
				text-align: center;
				height: 80rpx;
				line-height: 80rpx;
				color: #fff;
				background-color: $brand-theme-color;
				border-radius: 48rpx;
				font-weight: bold;
			}
		}

		/* 添加空状态提示样式 */
		.empty-tip {
			padding: 40rpx;
			text-align: center;
			color: $text-font-color-3;
			font-size: 28rpx;
		}
	}
</style>